<!-- HyProgBar - 顶部进度条遮罩层及相关内容（引言）
 Code Type: HTML
 跳转前记录实际进度，加载后精确衔接，动画使用 requestAnimationFrame
-->
<div id="pageLeavingMask" class="hyplus-unselectable" style="opacity: 1; display: none">
    <div id="pageLeavingDotsWrapper">
        <div class="pageLeavingDot"></div>
        <div class="pageLeavingDot"></div>
        <div class="pageLeavingDot"></div>
    </div>
    <div id="pageLeavingQuoteWrapper">
        <div id="pageLeavingQuote"></div>
    </div>
</div>
<div id="pageLeavingTopBar" style="display: none">
    <div id="pageLeavingTopBarInner"></div>
</div>
<style>
    #pageLeavingMask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: #fff;
        z-index: 1111110;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        opacity: 1;
        transition: opacity 0.38s cubic-bezier(0.4, 0, 0.2, 1);
        pointer-events: auto;
        overflow: hidden;
        touch-action: none;
    }
    #pageLeavingDotsWrapper {
        width: 100%;
        text-align: center;
        margin-bottom: 24px;
        height: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
    }
    .pageLeavingDot {
        width: 8px;
        height: 8px;
        background: #2196f3;
        border-radius: 50%;
        animation: pageLeavingDotBounce 1.4s infinite ease-in-out;
    }
    .pageLeavingDot:nth-child(1) {
        animation-delay: -0.32s;
    }
    .pageLeavingDot:nth-child(2) {
        animation-delay: -0.16s;
    }
    @keyframes pageLeavingDotBounce {
        0%,
        80%,
        100% {
            transform: scale(0.6);
            opacity: 0.6;
        }
        40% {
            transform: scale(1);
            opacity: 1;
        }
    }
    #pageLeavingQuoteWrapper {
        width: 100%;
        text-align: center;
    }
    #pageLeavingQuote {
        font-family: "行楷", "楷体", "STKaiti", "华文楷体", "仿宋", "STFangsong", "黑体", "STHeiti", sans-serif;
        font-size: 28px;
        color: #333;
        padding: 20px;
        max-width: 80%;
        margin: 0 auto;
        line-height: 1.8;
        letter-spacing: 1px;
    }
    #pageLeavingTopBar {
        position: fixed;
        left: 0;
        top: 0;
        width: 100vw;
        height: 4px;
        background: transparent;
        z-index: 1111111;
        display: block;
        pointer-events: none;
        opacity: 1;
        transition: opacity 0.2s ease-out;
    }
    #pageLeavingTopBarInner {
        height: 100%;
        width: 0%;
        background: #2196f3;
        transition: width 0.2s linear;
    }
</style>
<script>
    // 修复前进/后退时进度条卡住的问题
    window.addEventListener("pageshow", function (e) {
        if (e.persisted) {
            sessionStorage.removeItem("pageLeavingNeedShow");
            sessionStorage.removeItem("pageLeavingProgress");
            var mask = document.getElementById("pageLeavingMask");
            var topBar = document.getElementById("pageLeavingTopBar");
            if (mask) {
                mask.style.display = "none";
            }
            if (topBar) {
                topBar.style.display = "none";
            }
        }
    });
    (function () {
        // 简化版：仅跳转后显示进度条和遮罩，无跳转前动画
        const MASK_ID = "pageLeavingMask";
        const QUOTE_STORAGE_KEY = "localQuotes";
        const QUOTE_URL = "https://www.hyperplasma.top/hpsrc/selection.txt";
        const QUOTE_CUR_KEY = "pageLeavingQuoteCur";
        const mask = document.getElementById(MASK_ID);
        const quoteEl = document.getElementById("pageLeavingQuote");
        const topBar = document.getElementById("pageLeavingTopBar");
        const topBarInner = document.getElementById("pageLeavingTopBarInner");
        let quotesCache = null;
        let progressRaf = null;

        function showQuote(q) {
            quoteEl.textContent = q || "正在加载...";
        }
        function getLocalQuotes() {
            const stored = localStorage.getItem(QUOTE_STORAGE_KEY);
            if (!stored) return null;
            try {
                const arr = JSON.parse(stored);
                return Array.isArray(arr) && arr.length ? arr : null;
            } catch (e) {
                localStorage.removeItem(QUOTE_STORAGE_KEY);
                return null;
            }
        }
        function setLocalQuotes(arr) {
            try {
                if (Array.isArray(arr) && arr.length) localStorage.setItem(QUOTE_STORAGE_KEY, JSON.stringify(arr));
            } catch (e) {}
        }
        function randomQuote(arr) {
            if (!arr || !arr.length) return "正在加载...";
            return arr[Math.floor(Math.random() * arr.length)];
        }
        function loadAndCacheQuotes(cb) {
            if (quotesCache) {
                cb(quotesCache);
                return;
            }
            const localQuotes = getLocalQuotes();
            if (localQuotes) {
                quotesCache = localQuotes;
                cb(localQuotes);
                return;
            }
            fetch(QUOTE_URL)
                .then((res) => res.text())
                .then((text) => {
                    const arr = text
                        .split("\n")
                        .map((q) => q.trim())
                        .filter(Boolean);
                    if (arr.length) {
                        setLocalQuotes(arr);
                        quotesCache = arr;
                        cb(arr);
                    } else {
                        cb(["正在加载..."]);
                    }
                })
                .catch(() => cb(["正在加载..."]));
        }
        function setTopBarProgress(val) {
            val = Math.max(0, Math.min(100, Math.round(val)));
            topBarInner.style.width = val + "%";
        }
        function clearAllAnim() {
            if (progressRaf !== null) {
                cancelAnimationFrame(progressRaf);
                progressRaf = null;
            }
        }
        function showMaskAndQuote() {
            mask.style.display = "flex";
            mask.style.opacity = "1";
            const cur = sessionStorage.getItem(QUOTE_CUR_KEY);
            if (cur) showQuote(cur);
            else {
                loadAndCacheQuotes((arr) => {
                    const q = randomQuote(arr);
                    sessionStorage.setItem(QUOTE_CUR_KEY, q);
                    showQuote(q);
                });
            }
            // 最多2秒后隐藏中央内容和白色背景
            setTimeout(hideMaskCenter, 5000);
        }
        // 隐藏中央内容和白色背景，但不隐藏顶部条
        function hideMaskCenter() {
            if (!mask) return;
            mask.style.transition = "opacity 0.38s cubic-bezier(0.4, 0, 0.2, 1)";
            mask.style.opacity = "0";
            setTimeout(function () {
                mask.style.display = "none";
            }, 400);
        }
        // 重置顶部条进度
        function resetTopBar(cb) {
            setTopBarProgress(0);
            if (cb) cb();
        }
        function showTopBar(startVal = 0) {
            topBar.style.display = "block";
            setTopBarProgress(startVal);
            void topBarInner.offsetWidth;
        }
        function animateTopBar(from, to, duration, cb) {
            clearAllAnim();
            let start = from,
                end = to;
            let t0 = performance.now();
            function step(now) {
                let dt = now - t0;
                let percent = Math.min(1, dt / duration);
                let val = Math.round(start + (end - start) * percent);
                setTopBarProgress(val);
                if (percent < 1) {
                    progressRaf = requestAnimationFrame(step);
                } else {
                    setTopBarProgress(end);
                    progressRaf = null;
                    if (cb) cb();
                }
            }
            progressRaf = requestAnimationFrame(step);
        }
        function handleNewPage() {
            showMaskAndQuote();
            showTopBar(1);

            let resourcesTotal = 0;
            let resourcesLoaded = 0;
            let lastProgress = 5;

            // 监听所有资源的加载情况
            const observer = new PerformanceObserver((list) => {
                for (const entry of list.getEntries()) {
                    if (entry.entryType === "resource") {
                        resourcesTotal++;
                    }
                }
            });
            observer.observe({ entryTypes: ["resource"] });

            // 监听各个资源加载完成事件
            const onResourceLoad = () => {
                resourcesLoaded++;
                const progress = Math.min(95, 5 + Math.round((resourcesLoaded / Math.max(1, resourcesTotal)) * 90));
                if (progress > lastProgress) {
                    animateTopBar(lastProgress, progress, 200);
                    lastProgress = progress;
                }
            };

            // 监听图片加载
            document.querySelectorAll("img").forEach((img) => {
                if (!img.complete) {
                    resourcesTotal++;
                    img.addEventListener("load", onResourceLoad);
                    img.addEventListener("error", onResourceLoad);
                }
            });

            // 监听样式表加载
            document.querySelectorAll('link[rel="stylesheet"]').forEach((link) => {
                if (!link.sheet) {
                    resourcesTotal++;
                    link.addEventListener("load", onResourceLoad);
                    link.addEventListener("error", onResourceLoad);
                }
            });

            // 监听脚本加载
            document.querySelectorAll("script[src]").forEach((script) => {
                if (!script.loaded) {
                    resourcesTotal++;
                    script.addEventListener("load", onResourceLoad);
                    script.addEventListener("error", onResourceLoad);
                }
            });

            // DOMContentLoaded 事件
            if (document.readyState === "loading") {
                document.addEventListener("DOMContentLoaded", () => {
                    const progress = Math.max(lastProgress, 30);
                    animateTopBar(lastProgress, progress, 200);
                    lastProgress = progress;
                });
            }

            // 页面完全加载完成
            window.addEventListener("load", () => {
                animateTopBar(lastProgress, 100, 250, function () {
                    observer.disconnect();
                    // 等待一小段时间后淡出进度条
                    setTimeout(() => {
                        topBar.style.opacity = "0";
                        setTimeout(() => {
                            topBar.style.display = "none";
                            setTopBarProgress(0);
                        }, 200);
                    }, 100);
                });
                // 隐藏中央内容和白色背景
                hideMaskCenter();
            });
        }
        handleNewPage();
    })();
</script>
